﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Easydp.Models.Entities;
using Easydp.Controllers;
using System.Configuration;
using System.Text;
using System.IO;
namespace Web.Views.AilPay
{
    public partial class AliPay : System.Web.UI.Page
    {
        TT_Orders orderObj;
        TT_PushFee pushfeeObj;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.Form["ctl00$ContentPlace$OrderID"]))
                Response.Redirect("../Shared//ErrorPage.aspx?Error=parameter_error");
            OrderController orderControl = new OrderController();
            orderObj = orderControl.GetWaitPayOrder(Request.Form["ctl00$ContentPlace$OrderID"].ToString());
            pushfeeObj = (new PushFeeController()).GetModel(Convert.ToInt32(Request.Form["ctl00$ContentPlace$OrderID"]));
            if(orderObj==null)
                Response.Redirect("../Shared//ErrorPage.aspx?Error=object_null");
        }
        
        private void BindPayData()
        {
           AccountInfoController accountInfo = new AccountInfoController();
           TT_AccountInfo accountObj= accountInfo.GetModel(orderObj.AgentID);

           #region 业务参数赋值
           //按时构造订单号;
           //System.DateTime currentTime = new System.DateTime();
           //currentTime = System.DateTime.Now;
           //string out_trade_no = currentTime.ToString("g");
           //out_trade_no = out_trade_no.Replace("-", "");
           //out_trade_no = out_trade_no.Replace(":", "");
           //out_trade_no = out_trade_no.Replace(" ", "");
           //业务参数赋值；
            string gateway = "https://www.alipay.com/cooperate/gateway.do?";//'支付接口
            string service = "create_direct_pay_by_user";
           
            string sign_type = "MD5";
            string subject ="火车票";	//subject		商品名称
            string body = string.Format("订单号:{0},行程:{1}-{2}",orderObj.OrderNum,orderObj.StartStation,orderObj.EndStation) ;		//body			商品描述    
            string payment_type ="1";             //支付类型	
            string total_fee = orderObj.PayMoney.ToString("F"); //总金额					0.01～50000.00
            string show_url = "http://www.easydp.net";
            string seller_email = accountObj.AccountCode;   //卖家账号
            string partner = "";                //partner		合作伙伴ID			保留字段
            string key = "zhiasv6quoplnykcii4vo3iv3afvh6si";              //partner账户的支付宝安全校验码
            string merchantCallbackURL = "";
            string NotifyType = ConfigurationManager.AppSettings["NotifyType"];
            string buyer_email = pushfeeObj.OtherAccount; //卖方EMAIL
            if (NotifyType == "域名")
            {
                merchantCallbackURL = "http://" + Request.Url.Authority + "/Views/AilPay/AliPayReceive.aspx|http://" + Request.Url.Authority + "/Views/AilPay/AliPayNotify.aspx";
            }
            else
            {
                string IPAddress = ConfigurationManager.AppSettings["IPAddress"];
                merchantCallbackURL = "http://" + IPAddress + "/Views/AilPay/AliPayReceive.aspx|http://" + IPAddress + "/Views/AilPay/AliPayNotify.aspx";
            }
            string return_url = merchantCallbackURL.Split(new char[] { '|' })[0].ToString();				//服务器通知返回接口
            string notify_url = merchantCallbackURL.Split(new char[] { '|' })[1].ToString();				//服务器通知返回接口     
            string out_trade_no = orderObj.OrderNum;

            //提成信息
            string royalty_type = string.Empty;
            //获得订单的提成信息
            string royalty_parameter = string.Empty;
            string parameter = GetRoyaltyParameter();

            if (parameter.Length > 0)
            {
                royalty_parameter = parameter.ToString();
                royalty_type = "10";
            }
            AliPayCode ap = new AliPayCode();
            string aliay_url = ap.CreatUrl(
                gateway,
                service,
                partner,
                sign_type,
                out_trade_no,
                subject,
                body,
                payment_type,
                total_fee,
                show_url,
                seller_email,
                buyer_email,
                key,
                return_url,
                notify_url,
                royalty_type,
                royalty_parameter
                );
            //写入日志   
            StringBuilder meg = new StringBuilder("\r\n开始支付:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";订单号：" + orderObj.OrderID + ";向支付宝发送支付请求,url:" + aliay_url);
            try
            {
                //更新订单
                meg.AppendLine("数据库写入成功!");
            }
            catch (Exception ex)
            {
                meg.AppendLine("数据库写入失败:");
                meg.Append(ex.Message);
            }
            AliPayCode.WriteLog(meg.ToString());
            Response.Redirect(aliay_url);

            #endregion
        }


        private string GetRoyaltyParameter()
        {
            StringBuilder parameter = new StringBuilder();
            if (pushfeeObj != null)
            {
                //售票点分账
                parameter.AppendFormat("{0}^{1}",pushfeeObj.AgentAccount,pushfeeObj.AgentGet);
                decimal agentGet = orderObj.Amount * orderObj.UnitPrice + 4 + orderObj.TotalMoney;
                parameter.AppendFormat("^{0}张price:{1}other:{2}Total:{3}actual:{4}", orderObj.Amount, orderObj.UnitPrice, orderObj.TotalMoney, agentGet, pushfeeObj.AgentGet);

                //平台分润
                parameter.AppendFormat("|{0}^{1}^{2}", pushfeeObj.PlatformAccount, pushfeeObj.PlatformGet,"平台交易费;orderid:"+orderObj.OrderNum);

                if (pushfeeObj.OtherGet > 0)
                {
                    //其他支付费用
                    parameter.AppendFormat("|{0}^{1}^{2}", pushfeeObj.OtherAccount, pushfeeObj.OtherGet, "支付费用;orderid:" + orderObj.OrderNum);
                }
            }
            return parameter.ToString();

        }



        
    }
}
